<?php

namespace app\api\controller\Product;

use think\Controller;
use think\Request;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('Product.Order');

        $this->OrderProductModel = model('Product.OrderProduct');
        
        $this->CartModel = model('Product.Cart');

        $this->UserModel = model('User.User');

        $this->RecordModel = model('User.Record');

        $this->ProductModel = model('Product.Product');
    }

    public function index()
    {
        $userid = $this->request->param('userid');

        $status = $this->request->param('status');

        $where = [];

        if(!empty($userid))
        {
            $where['userid'] = $userid;
        }

        if($status != 0)
        {
            $where['status'] = $status;
        }

        $orderList = $this->OrderModel->where($where)->select();

        foreach($orderList as $item)
        {
            $OrderProduct = $this->OrderProductModel->with('product')->where('orderid',$item['id'])->select();

            $item['OrderProduct'] = $OrderProduct;
        }

        $this->success('查询成功',null,$orderList);
    }

    public function confirm()
    {
        $userid = $this->request->param('userid');

        $ids = $this->request->param('ids');

        $addrid = $this->request->param('addrid');

        $content = $this->request->param('content');

        $CartList = model('Product.Cart')->with('product')->whereIn('cart.id',$ids)->where(['userid' => $userid])->select();

        $user = model('User.User')->find($userid);

        $address = model('User.Address')->find($addrid);

        if(!$CartList)
        {
            $this->error('所选的商品不存在，请重新选择');
        }

        if(!$user)
        {
            $this->error('用户不存在，请注册');
        }

        if(!$address)
        {
            $this->error('所选的收货地址不存在，请重新选择');
        }

        /* 
            购物车 => 删除
            订单表 => 新增订单 1
            订单商品 => 把购物车的数据添加订单商品表 1
            更新用户积分
            新增消费记录
            更新商品库存
        */


        // 订单总价
        $total = 0;

        foreach ($CartList as $key => $item) {
            // 购买商品数量是否小于商品库存
            if($item['nums'] > $item['product']['stock'])
            {
                $this->error($item['product']['name'] . '商品库存不足，请重新选择');
            }

            // 用户的积分是否足够
            $point = bcsub($user['point'],$item['total']);

            if($point < 0)
            {
                $this->error('您的积分不足，请及时充值');
            }

            // 计算出订单总价
            $total += $item['total'];
            
        }

        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();
        $this->CartModel->startTrans();
        $this->UserModel->startTrans();
        $this->RecordModel->startTrans();
        $this->ProductModel->startTrans();

        // 订单数据
        $OrderData = [
            'total' => $total,
            'userid' => $userid,
            'addrid' =>  $addrid,
            'code' => build_code('ASK'),
            'content' => $content,
            'status' => 1
        ];

        $OrderStatus = $this->OrderModel->validate('common/Product/Order')->save($OrderData);

        if($OrderStatus === FALSE)
        {
            $this->error($this->OrderModel->getError());
        }

        // 订单商品数据
        $OrderProductData = [];

        foreach($CartList as $item)
        {
            $OrderProductData[] = [
                'orderid' => $this->OrderModel->id,
                'proid' => $item['product']['id'],
                'nums' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
                'userid' => $userid
            ];
        }
        
        $OrderProductStatus = $this->OrderProductModel->validate('common/Product/OrderProduct')->saveAll($OrderProductData);

        if($OrderProductStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->error($this->OrderProductModel->getError());
        }


        // 删除购物车
        $CartStatus = $this->CartModel->WhereIn('id',$ids)->delete();

        if($CartStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error($this->CartModel->getError());
        }

        // 更新用户积分
        $UserData = [
            'id' => $userid,
            'point' => bcsub($user['point'],$total)
        ];

        $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

        if($UserStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->error($this->UserModel->getError());
        }

        // 新增消费记录
        $RecordData = [
            'point' => $total,
            'content' => "您的商品订单{$OrderData['code']}共消费了{$total}积分",
            'state' => 5,
            'userid' => $userid
        ];

        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

        if($RecordStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        // 更新商品的库存
        $ProductData = [];

        foreach($CartList as $item)
        {
            $ProductData[] = [
                'id' => $item['product']['id'],
                'stock' => bcsub($item['product']['stock'],$item['nums'])
            ];
        }

        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if($ProductStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error($this->ProductModel->getError());
        }


        if($OrderStatus === FALSE || $OrderProductStatus === FALSE || $CartStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->ProductModel->rollback();
            $this->error('下单失败');
        }else{
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->CartModel->commit();
            $this->UserModel->commit();
            $this->RecordModel->commit();
            $this->ProductModel->commit();
            $this->success('下单成功','/order/order/info',['orderid' => $this->OrderModel->id]);
        }






    }

    public function info()
    {
        $userid = $this->request->param('userid');

        $orderid = $this->request->param('orderid');

        $user = $this->UserModel->find($userid);

        if(!$user)
        {
            $this->error('用户不存在，请重新注册');
        }

        /* 
            订单表
            订单商品表 （主表）
            商品表
            用户收货地址
        */

        // 订单
        $order = $this->OrderModel->find($orderid);

        // 订单商品
        $OrderProduct = $this->OrderProductModel->with('product')->where(['orderid' => $orderid])->select();

        // 收货地址
        $Address = model('User.Address')->with(['provinces','citys','districts'])->find($order['addrid']);
        
        if(!$order || !$OrderProduct || !$Address)
        {
            $this->error('订单不存在，请重新选择');
        }

        $data = [
            'order' => $order,
            'OrderProduct' => $OrderProduct,
            'address' => $Address
        ];

        $this->success('查询成功',null,$data);

    }
}
